package com.das.mechanic_base.adapter.alone;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;

import com.das.mechanic_base.R;
import com.das.mechanic_base.app.X3AppRouterConstants;
import com.das.mechanic_base.app.X3Constent;
import com.das.mechanic_base.bean.alone.NewServiceHeaderBean;
import com.das.mechanic_base.app.X3RouterCenter;
import com.das.mechanic_base.utils.X3DateUtils;
import com.das.mechanic_base.utils.X3GlideNewUtils;
import com.das.mechanic_base.utils.X3ScreenUtils;
import com.das.mechanic_base.utils.SpHelper;
import com.das.mechanic_base.utils.X3StringUtils;

import java.util.ArrayList;
import java.util.List;

public class X3NewSearchServiceItemAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private List<NewServiceHeaderBean.AlreadyInPlanListBean> mList;

    private Context mContext;

    private String km;

    private long carId;

    /**
     * 空数据时，显示空布局类型
     */
    private final int EMPTY_VIEW = 1;

    /**
     * 控制空布局的显隐
     */
    private int mEmptyType = 0;
    private int afterDay;


    public X3NewSearchServiceItemAdapter(Context mContext) {
        this.mList = new ArrayList<>();
        this.mContext = mContext;
    }

    public void changeCarId(long carId) {
        this.carId = carId;
    }

    public void changeServiceItem(List<NewServiceHeaderBean.AlreadyInPlanListBean> mList) {
        this.mList = mList;
        km = (String) SpHelper.getData(X3Constent.MILEAGEUNIT, "km");

        if (X3StringUtils.isListEmpty(mList)) {
            mEmptyType = 1;
        }else {
            mEmptyType = 0;
        }
        notifyDataSetChanged();
    }

    public void changeDeleteMiles(NewServiceHeaderBean.AlreadyInPlanListBean modifyBean,int position) {
        if (modifyBean == null) {
            return;
        }
        mList.remove(position);
        mList.add(position,modifyBean);
        notifyItemChanged(position);
    }

    public void changeMilesService(NewServiceHeaderBean.AlreadyInPlanListBean serviceListBean) {
        int refreshIndex = -1;
        for (int i = 0; i < mList.size(); i++) {
            if (serviceListBean.serviceBaseSn.equals(mList.get(i).serviceBaseSn)) {
                NewServiceHeaderBean.AlreadyInPlanListBean serviceBaseEntityBean = mList.get(i);
                mList.remove(i);
                serviceBaseEntityBean.seleced = true;
                serviceBaseEntityBean.warningDate = serviceListBean.warningDate;
                serviceBaseEntityBean.reductionType = serviceListBean.reductionType;
                serviceBaseEntityBean.nextReplaceCycleKm = serviceListBean.nextReplaceCycleKm;
                mList.add(i,serviceBaseEntityBean);
                refreshIndex = i;
                break;
            }
        }

        if (refreshIndex == -1) {
            return;
        }
        notifyItemChanged(refreshIndex);
    }

    /**
     * 删除推荐服务需要刷新
     * @param position
     */
    public void deleteService(int position,boolean isDelete,boolean isBackNotify) {
        NewServiceHeaderBean.AlreadyInPlanListBean headerBean = mList.get(position);
        if (!isDelete) {
            if (iOnClickService != null) {
                iOnClickService.iOnCuteService(mList.get(position).seleced,mList.get(position),position);
            }
            return;
        }
        mList.remove(position);
        headerBean.seleced = (!headerBean.seleced);
        mList.add(position,headerBean);
        if (isBackNotify) {
            if (iOnClickService != null) {
                iOnClickService.iOnCuteService(!mList.get(position).seleced,mList.get(position),position);
            }
        }
        notifyItemChanged(position);
    }

    public List<NewServiceHeaderBean.AlreadyInPlanListBean> getmList(){
        return mList;
    }

    public void deleteAllService(int position) {
        NewServiceHeaderBean.AlreadyInPlanListBean headerBean = mList.get(position);
        mList.remove(position);
        headerBean.seleced = !headerBean.seleced;
        mList.add(position,headerBean);
        notifyItemChanged(position);
    }

    public void refreshAddService(int position,double currentMiles,double perMiles) {
        for (int i = 0; i < mList.size(); i++) {
            NewServiceHeaderBean.AlreadyInPlanListBean serviceBean = mList.get(i);
            mList.remove(i);
            serviceBean.perMiles = perMiles;
            serviceBean.currentMiles = currentMiles;
            if (i == position) {
                serviceBean.seleced = !serviceBean.seleced;
            }
            mList.add(i,serviceBean);

        }
        notifyDataSetChanged();
    }

    public void refreshMiles(double currentMiles,double perMiles) {
        for (int i = 0; i < mList.size(); i++) {
            NewServiceHeaderBean.AlreadyInPlanListBean serviceBean = mList.get(i);
            mList.remove(i);
            serviceBean.perMiles = perMiles;
            serviceBean.currentMiles = currentMiles;
            mList.add(i,serviceBean);

        }
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        switch (viewType) {
            case 0:
                return new AloneServiceItemHolder(LayoutInflater.from(mContext).inflate(R.layout.x3_alone_service_item_select,parent,false));
            case 1:
                return new EmptyHolder(LayoutInflater.from(mContext).inflate(R.layout.x3_empty_record_item, parent, false));
        }
        return new AloneServiceItemHolder(LayoutInflater.from(mContext).inflate(R.layout.x3_alone_service_item_select,parent,false));
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {

        if (getItemViewType(position) == 0) {

            AloneServiceItemHolder holder1 = (AloneServiceItemHolder) holder;

            RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) holder.itemView.getLayoutParams();

            if (position == mList.size() - 1) {
                layoutParams.bottomMargin = X3ScreenUtils.dipToPx(40,mContext);
            }else {
                layoutParams.bottomMargin = 0;
            }
            holder.itemView.setLayoutParams(layoutParams);

            X3GlideNewUtils.loadRoundOriginCornerImage(mContext, X3StringUtils.getImageUrl(mList.get(position).pictureResourceUrl),holder1.iv_icon, X3ScreenUtils.dipToPx(8,mContext), R.mipmap.x3_service_normal_bg);

            holder1.tv_title.setText(mList.get(position).serviceBaseName + "");

            holder1.tv_content.setVisibility(mList.get(position).seleced ? View.VISIBLE : View.GONE);
            holder1.tv_content_notice.setVisibility(mList.get(position).seleced ? View.VISIBLE : View.GONE);

            if (mList.get(position).seleced) {
                holder1.iv_cute.setImageResource(R.mipmap.x3_service_cute_icon);

                int nextReplaceCycleKm = X3StringUtils.getInt(mList.get(position).nextReplaceCycleKm);
                if(mList.get(position).perMiles == 0.0 || mList.get(position).perMiles ==0.00){
                    afterDay = 0;
                }else {
                    afterDay = X3StringUtils.getInt((nextReplaceCycleKm - mList.get(position).currentMiles) / mList.get(position).perMiles);
                }

                if (afterDay <= 0) {
                    holder1.tv_content_notice.setVisibility(View.GONE);
                    holder1.tv_content.setTextColor(Color.parseColor("#F64458"));
                    holder1.tv_content.setBackground(ContextCompat.getDrawable(mContext,R.drawable.x3_service_notice_mile_or_time_asap_shape));
                    holder1.tv_content.setText(mContext.getString(R.string.x3_now_to_work));
                }else {

                    holder1.tv_content.setTextColor(Color.parseColor("#FFC602"));
                    holder1.tv_content.setBackground(ContextCompat.getDrawable(mContext,R.drawable.x3_service_notice_mile_or_time_shape));

                    String remildType = mList.get(position).reductionType;
                    if ("TIME".equals(remildType)) {
                        // 按保养总时间
                        String warningDate = mList.get(position).warningDate;
                        String showAloneTime = X3DateUtils.getShowAloneTime(warningDate);
                        nextReplaceCycleKm = X3StringUtils.getInt(mList.get(position).perMiles * afterDay + mList.get(position).currentMiles);
                        holder1.tv_content_notice.setText(String.format(mContext.getString(R.string.x3_add_service_touch_content),nextReplaceCycleKm + km));
                        holder1.tv_content.setText(showAloneTime);
                    }else {
                        // 按保养总里程
                        String addDaysMonth = X3DateUtils.getAddDaysMonth(afterDay);
                        holder1.tv_content.setText(String.format(mContext.getString(R.string.x3_add_service_touch_content),nextReplaceCycleKm + km));
                        holder1.tv_content_notice.setText(addDaysMonth);
                    }
                }

                holder.itemView.setOnClickListener(view -> {
                    if (iOnClickService != null) {
                        NewServiceHeaderBean.AlreadyInPlanListBean entityBean = mList.get(position);
                        if(X3StringUtils.isEmpty(entityBean.reductionType)){
                            iOnClickService.iOnShowChangeService(entityBean.serviceBaseSn,"MILE",entityBean.currentMiles,entityBean.perMiles);
                        }else {
                            iOnClickService.iOnShowChangeService(entityBean.serviceBaseSn,entityBean.reductionType,entityBean.currentMiles,entityBean.perMiles);
                        }
                    }
                });
            }else {
                holder1.iv_cute.setImageResource(R.mipmap.x3_service_add_icon);
                holder.itemView.setOnClickListener(null);
            }

            /**
             * 加还是减
             */
            holder1.iv_cute.setOnClickListener(view -> {
                // 是否把服务项目删除掉
                boolean isCute = mList.get(position).seleced;
                if (isCute) {
                    if (iOnClickService != null) {
                        iOnClickService.iOnShowDelete(position,mList.get(position).serviceBaseSn);
                    }
                }else {
                    deleteService(position,false,true);
                }
            });

            holder1.tv_title.setOnClickListener(v -> {
                Bundle bundle = new Bundle();
                bundle.putString("path", X3Constent.SERVICE_INFO_PAGE_URL + mList.get(position).serviceBaseSn + "&carId=" + carId);
                bundle.putString("title","服务详情介绍页");
                X3RouterCenter.startNavigate(X3AppRouterConstants.Router.GROUND_PUSH,bundle);

                // 跳转到服务详情介绍页
//                Intent intent = new Intent(mContext, GroundPushActivity.class);
//                intent.putExtra("path", Constent.SERVICE_INFO_PAGE_URL + mList.get(position).serviceBaseSn + "&carId=" + carId);
//                intent.putExtra("title","服务详情介绍页");
//                mContext.startActivity(intent);
            });
            holder1.iv_icon.setOnClickListener(v -> {
                // 跳转到服务详情介绍页
                Bundle bundle = new Bundle();
                bundle.putString("path", X3Constent.SERVICE_INFO_PAGE_URL + mList.get(position).serviceBaseSn + "&carId=" + carId);
                bundle.putString("title","服务详情介绍页");
                X3RouterCenter.startNavigate(X3AppRouterConstants.Router.GROUND_PUSH,bundle);
            });
        }else {
            EmptyHolder emptyHolder = (EmptyHolder) holder;
            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) emptyHolder.tv_empty.getLayoutParams();
            layoutParams.topMargin = X3ScreenUtils.dipToPx(50,mContext);
            emptyHolder.tv_empty.setLayoutParams(layoutParams);

        }
    }

    IOnClickService iOnClickService;

    public void setiOnClickService(IOnClickService iOnClickService) {
        this.iOnClickService = iOnClickService;
    }

    public interface IOnClickService {

        /**
         * 是否增加还是削减项目
         */
        void iOnCuteService(boolean isCute,NewServiceHeaderBean.AlreadyInPlanListBean serviceBean,int position);

        /**
         * 通过sn查询本地缓存中数据 更改里程
         * @param sn
         */
        void iOnShowChangeService(String sn,String type,double currentMiles,double perMiles);

        /**
         * 删除推荐服务时需要弹框提醒
         * @param position
         * @param sn
         */
        void iOnShowDelete(int position,String sn);
    }

    @Override
    public int getItemCount() {
        if (X3StringUtils.isListEmpty(mList)) {
            return mEmptyType;
        }
        return mList.size();
    }

    @Override
    public int getItemViewType(int position) {
        if (mEmptyType == EMPTY_VIEW) {
            //空布局的类型
            return 1;
        }
        return 0;
    }

    class AloneServiceItemHolder extends RecyclerView.ViewHolder {
        TextView tv_title;
        ImageView iv_icon;
        TextView tv_content;
        ImageView iv_cute;
        TextView tv_content_notice;
        public AloneServiceItemHolder(@NonNull View itemView) {
            super(itemView);
            tv_title = itemView.findViewById(R.id.tv_title);
            iv_icon = itemView.findViewById(R.id.iv_icon);
            tv_content = itemView.findViewById(R.id.tv_content);
            iv_cute = itemView.findViewById(R.id.iv_cute);
            tv_content_notice = itemView.findViewById(R.id.tv_content_notice);
        }
    }

    class EmptyHolder extends RecyclerView.ViewHolder {
        TextView tv_empty;
        public EmptyHolder(@NonNull View itemView) {
            super(itemView);
            tv_empty = itemView.findViewById(R.id.tv_empty);
        }
    }

}
